import React, {PropsWithChildren, useState} from "react"
import {Popover, SelectProps, Space} from "antd";
import RefreshableSelect from "./RefreshableSelect";
import {PopoverConfirmButtons} from "./PopoverConfirmButtons";
import {NumberIdAndName} from "../types/BasicModels";
import {getAllMarket} from "../apis/MarketsApi";

export interface SingleSelectConfirmPopoverProps extends PropsWithChildren{
    title:string
    onConfirm: (procurementSupplierId: any) => Promise<void>
    options:SelectProps["options"]
    onRefresh:()=>Promise<void>
}

const SingleSelectConfirmPopover: React.FC<SingleSelectConfirmPopoverProps> = (props) => {
    const [loading, setLoading] = useState(false)

    const [loaded, setLoaded] = useState(false)

    function load() {
        return props.onRefresh().then(response => {
            setLoaded(true)
        })
    }

    const [selectedValue, setSelectedValue] = useState<number>()
    let title = props.title;

    const [open,setOpen] = useState(false)
    return (
        <>
            <Popover trigger={"click"} title={title} open={open} onOpenChange={(open) => {
                if (open && !loaded) {
                    load()
                }
                setOpen(open)
            }} content={
                <Space direction={"vertical"}>
                    <RefreshableSelect showSearch onRefresh={load}
                                       placeholder={title}
                                       optionFilterProp={"label"}
                                       onChange={value => setSelectedValue(value)}
                                       options={props.options}/>
                    <PopoverConfirmButtons confirmButtonLoading={loading} confirmDisabled={!selectedValue} onConfirm={async () => {
                        setLoading(true)
                        try {
                            await props.onConfirm(selectedValue!!)
                        } finally {
                            setLoading(false)
                        }
                        setOpen(true)
                    }} onCancel={() => {
                        setOpen(false)
                    }}/>
                </Space>

            } children={props.children}/>
        </>
    )
}

export default SingleSelectConfirmPopover
